// 用于保存聊天记录的pinia store仓库
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { MessageType } from '@/types/enum/message'
import { gptMessageRole } from '@/types/enum/index'

export interface chatMsgInterface {
  msg: string
  type: MessageType
  name: string
  id: string | number
  isLoading: boolean
  chat_id?: number | string
}
export interface messageInterface {
  role: gptMessageRole
  content: string
}

export const useChatStore = defineStore('chat', () => {
  // 用于保存聊天记录，用于渲染给用户看时使用
  const initChatHistory: chatMsgInterface[] = [
    {
      msg: '你好呀!我是编程喵,欢迎和我一起学习编程!',
      type: MessageType.System,
      name: '编程喵',
      id: 1,
      isLoading: false,
      chat_id: -1
    }
  ]
  const initMessages: messageInterface[] = [
    {
      role: gptMessageRole.user,
      content:
        '你是一个叫编程喵的中学生编程助手。旨在帮助我学习Python编程。\
        如果我像你提问其他的问题请你提醒我专注于Python编程中。\
        请你耐心的回复我,语气尽可能可爱有趣。'
    },
    {
      role: gptMessageRole.system,
      content: '好的!我是编程喵,欢迎和我一起学习编程!我会耐心的回复你喵~'
    }
  ]
  const chatHistory = ref<chatMsgInterface[]>(initChatHistory)

  const addChatMsg = (msg: chatMsgInterface) => {
    chatHistory.value.push(msg)
  }

  const setChatGptMessageLoading = () => {
    chatHistory.value[chatHistory.value.length - 1].isLoading = true
  }

  const setChatGptFinalResponse = (msg: string, chat_id: string | number) => {
    chatHistory.value[chatHistory.value.length - 1].isLoading = false
    chatHistory.value[chatHistory.value.length - 1].msg = msg
    chatHistory.value[chatHistory.value.length - 1].chat_id = chat_id
  }

  // 记录与chatGpt的互动列表, 发送api请求时使用
  const messages = ref<messageInterface[]>(initMessages)

  const getMessages = (): messageInterface[] => {
    return messages.value
  }
  const addMessageList = (msg: messageInterface) => {
    messages.value.push(msg)
  }

  const deleteFinalMessageResponse = () => {
    messages.value.pop()
  }

  return {
    chatHistory,
    messages,
    setChatGptFinalResponse,
    setChatGptMessageLoading,
    addChatMsg,
    addMessageList,
    deleteFinalMessageResponse,
    getMessages
  }
})
